//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { Button, ConfigProvider, Descriptions, message, Modal, Space, Tabs } from 'antd';
import { BrowserRouter, useLocation } from "react-router-dom";
import zhCN from 'antd/lib/locale/zh_CN';
import '@/styles/global.less';
import { createRoot } from 'react-dom/client';
import type { MailInfo } from "@/api/user_mail";
import { get_mail_detail, remove_mail, set_mail_state } from "@/api/user_mail";
import { get_session } from "@/api/user";
import { request } from "@/utils/request";
import { CloseSquareOutlined, PushpinFilled, PushpinOutlined } from "@ant-design/icons";
import { appWindow } from "@tauri-apps/api/window";
import moment from "moment";
import type * as NoticeType from '@/api/notice_type';
import { emit } from "@tauri-apps/api/event";
import { report_error } from "@/api/client_cfg";

const MailDetail = () => {
    const location = useLocation();
    const urlParams = new URLSearchParams(location.search);
    const mailId = urlParams.get("id") ?? "";

    const [mailInfo, setMailInfo] = useState<MailInfo | null>(null);
    const [textBody, setTextBody] = useState("");
    const [htmlBody, setHtmlBody] = useState("");

    const [onTop, setOnTop] = useState(true);
    const [showRemoveModal, setShowRemoveModal] = useState(false);

    const loadMailInfo = async () => {
        const sessionId = await get_session();
        const res = await request(get_mail_detail({
            session_id: sessionId,
            mail_id: mailId,
        }));
        setMailInfo(res.info);
        setTextBody(res.text_body);
        setHtmlBody(res.html_body);
    };

    const removeMail = async () => {
        const sessionId = await get_session();
        await request(remove_mail({
            session_id: sessionId,
            mail_id: mailId,
        }));
        const notice: NoticeType.AllNotice = {
            ClientNotice: {
                RemoveMailNotice: {
                    mailId: mailId,
                },
            }
        };
        await emit("notice", notice);
        appWindow.close();
    };

    const markHasRead = async (hasRead: boolean) => {
        const sessionId = await get_session();
        await request(set_mail_state({
            session_id: sessionId,
            mail_id: mailId,
            has_read: hasRead,
        }));
        const notice: NoticeType.AllNotice = {
            ClientNotice: {
                UpdateMailStateNotice: {
                    mailId: mailId,
                    hasRead: hasRead,
                },
            }
        };
        await emit("notice", notice);
        if (mailInfo != null) {
            setMailInfo({
                ...mailInfo,
                has_read: hasRead,
            });
        }
    };

    useEffect(() => {
        if (mailId != "") {
            loadMailInfo();
        }
    }, [mailId]);

    return (
        <div style={{
            backgroundColor: "white",
            width: "100wh",
            height: "100vh",
            overflowY: "scroll",
            cursor: "move",
            border: "1px solid #e4e4e8"
        }} data-tauri-drag-region>
            <div style={{ position: "relative", height: "30px", paddingTop: "10px" }} data-tauri-drag-region>
                <div style={{ position: "absolute", left: "10px", fontSize: "16px", fontWeight: 700 }}>邮件正文</div>
                <Space style={{ position: "absolute", right: "20px" }}>
                    <Button type="text" icon={onTop ? <PushpinFilled style={{ fontSize: "24px" }} title='取消置顶' /> : <PushpinOutlined style={{ fontSize: "24px" }} title='置顶' />} onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        if (onTop) {
                            appWindow.setAlwaysOnTop(false).then(() => setOnTop(false));
                        } else {
                            appWindow.setAlwaysOnTop(true).then(() => setOnTop(true));
                        }
                    }} />
                    <Button type="text" icon={<CloseSquareOutlined style={{ fontSize: "24px" }} title="关闭" />} onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        appWindow.close();
                    }} />
                </Space>
            </div>
            {mailInfo != null && (
                <Descriptions column={1} bordered labelStyle={{ width: "100px" }} style={{ marginTop: "10px" }}>
                    <Descriptions.Item label="发件人">{mailInfo.from_account}</Descriptions.Item>
                    <Descriptions.Item label="发送时间">{moment(mailInfo.time_stamp).format("YYYY-MM-DD HH:mm:ss")}</Descriptions.Item>
                    <Descriptions.Item label="标题">{mailInfo.title}</Descriptions.Item>
                </Descriptions>
            )}
            {mailInfo != null && (
                <Tabs defaultActiveKey="html" style={{ padding: "0px 10px" }} type="card" tabBarStyle={{ fontWeight: 600, backgroundColor: "#f0f0f0" }}
                    tabBarExtraContent={
                        <Space>
                            <Button type="link" style={{ minWidth: "0px", padding: "0px 0px" }}
                                onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    markHasRead(!mailInfo.has_read);
                                }}>
                                {mailInfo.has_read == false && "标记为已读"}
                                {mailInfo.has_read == true && "标记为未读"}
                            </Button>
                            <Button type="link" danger style={{ minWidth: "0px", padding: "0px 0px" }}
                                onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    setShowRemoveModal(true);
                                }}>删除邮件</Button>
                        </Space>
                    }>
                    <Tabs.TabPane key="html" tab="富文本">
                        <div dangerouslySetInnerHTML={{ __html: htmlBody }} style={{ height: "calc(100vh - 240px)", overflowY: "scroll" }} />
                    </Tabs.TabPane>
                    <Tabs.TabPane key="text" tab="文本">
                        <pre dangerouslySetInnerHTML={{ __html: textBody }} style={{ height: "calc(100vh - 240px)", overflowY: "scroll" }} />
                    </Tabs.TabPane>
                </Tabs>
            )}
            {showRemoveModal == true && (
                <Modal open title="删除邮件" mask={false} width={300}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setShowRemoveModal(false);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeMail();
                    }}>
                    是否删除当前邮件?
                </Modal>
            )}
        </div>
    );
};

const App = () => {
    return (
        <ConfigProvider locale={zhCN}>
            <BrowserRouter>
                <MailDetail />
            </BrowserRouter>
        </ConfigProvider>
    );
}

const root = createRoot(document.getElementById('root')!);
root.render(<App />);

window.addEventListener('unhandledrejection', function (event) {
    // 防止默认处理（例如将错误输出到控制台）
    event.preventDefault();
    if (`${event.reason}`.includes("error trying to connect")) {
      return;
    }
    message.error(event?.reason);
    // console.log(event);
    try {
      report_error({
        err_data: `${event?.reason}`,
      });
    } catch (e) {
      console.log(e);
    }
  });